package com.hry.store.service.impl;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hry.store.common.BuyerCart;
import com.hry.store.common.Const;
import com.hry.store.dao.CartItemMapper;
import com.hry.store.pojo.CartItem;
import com.hry.store.service.CartService;
import com.hry.store.util.BigDecimalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartItemMapper cartItemMapper;

    @Override
    public void addItemToCookie(BuyerCart buyerCart, HttpServletResponse response) {
        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 将对象转换成json字符串
        Writer writer = new StringWriter();
        String json = null;
        try {
            om.writeValue(writer, buyerCart);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // 设计编码格式符合cookie存储形式
            json = URLEncoder.encode(writer.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Cookie cookie = new Cookie(Const.BUYER_CART, json);
        //设置path是可以共享cookie           
        cookie.setPath("/");
        // 设置Cookie过期时间: -1 表示关闭浏览器失效  0: 立即失效  >0: 单位是秒, 多少秒后失效            
        cookie.setMaxAge(24 * 60 * 60);
        // 5,Cookie写会浏览器           
        response.addCookie(cookie);
    }

    /**
     * 根据用户邮箱将商品添加到购物车中
     *
     * @param buyerCart
     * @param userEmail
     * @return
     */
    @Override
    public int addItemsByEmail(BuyerCart buyerCart, String userEmail) {
        CartItem cartItem = new CartItem();
        int resultCount = 0;
        CartItem item = new CartItem();
        for (CartItem cart : buyerCart.getItems()) {
            // 去数据库查找
            item = cartItemMapper.selectCartItem(cart.getProductId(), cart.getProductName(), cart.getVersionId(), cart.getColorName(), cart.getProductPrice(), userEmail);
            if (item == null) {
                cartItem.setUserEmail(userEmail);
                cartItem.setColorName(cart.getColorName());
                cartItem.setProductId(cart.getProductId());
                cartItem.setVersionId(cart.getVersionId());
                cartItem.setProductPrice(cart.getProductPrice());
                cartItem.setProductName(cart.getProductName());
                cartItem.setQuantity(cart.getQuantity());
                cartItem.setProductImg(cart.getProductImg());
                cartItem.setProductTotalPrice(cart.getProductTotalPrice());
                resultCount = cartItemMapper.insertByEmail(cartItem);
                return resultCount;
            } else {
                // 之前存的有更新数量 和总价
                int newCount = item.getQuantity() + cart.getQuantity();
                BigDecimal newTotalPrice = BigDecimalUtil.mul(newCount, item.getProductPrice().doubleValue());
                resultCount = cartItemMapper.updateCartItemCount(cart.getProductId(), cart.getProductName(), cart.getVersionId(), cart.getColorName(), cart.getProductPrice(), newCount, userEmail, newTotalPrice);
                return resultCount;
            }
        }
        return 0;
    }

    /**
     * 用户登录之后去数据库读取数据
     * @param userEmail
     * @return
     */
    @Override
    public List selectCartItemByEmail(String userEmail) {
        return cartItemMapper.selectCartItemByEmail(userEmail);
    }

    /**
     * 用户登录之后从数据库删除数据
     */
    @Override
    public int deleteFromMysql(Integer productId, String productName, BigDecimal productPrice, Integer versionId, String colorName, String userEmail) {
        return cartItemMapper.deleteFromMysql(productId, productName, productPrice, versionId, colorName, userEmail);
    }

    /**
     * 登陆之后重新设置数量

     */
    @Override
    public void updateNewCount(Integer productId, String productName, BigDecimal productPrice, Integer versionId, String colorName, Integer quantity, String userEmail) {
        BigDecimal newTotalPrice = BigDecimalUtil.mul(quantity, productPrice.doubleValue());
        cartItemMapper.updateNewCount(productId, productName, productPrice, versionId, colorName, quantity, userEmail, newTotalPrice);
    }

    /**
     * 单选 -- 单不选
     */
    @Override
    public int checked(Integer productId, String productName, BigDecimal productPrice, Integer versionId, String colorName, Integer checked, String userEmail) {
        return cartItemMapper.checked(productId, productName, productPrice, versionId, colorName, checked ,userEmail);
    }

    /**
     * 购物车查询选中的商品
     * @param userEmail
     * @return
     */
    @Override
    public List<CartItem> findByEmail(String userEmail) {
        return cartItemMapper.findByEmail(userEmail);
    }
}
